<template>
  <view class="container w100p common_wrap no-bg">
    <CommonHeader
      :title="title"
      color="#262728"
      :is-right="false"
      @goback="goback"
    ></CommonHeader>
    <view class="bg-color"></view>

    <!-- 购物车内容区 -->
    <view class="scroll-view-container">
      <scroll-view
        class="scroll-v"
        :scroll-top="scrollTop"
        scroll-y="true"
        :refresher-enabled="false"
        @scrolltolower="lower"
        @refresherrefresh="fresh"
        refresher-background="transparent"
        :refresher-triggered="isRefresher"
        @refresherrestore="store"
        @touchmove.stop
      >
        <view class="cart-wrapper">
          <u-swipe-action
            v-for="(item, index) in list"
            :key="index"
            :index="index"
            :options="options2"
            :btn-width="130"
            :show="item.show"
            @open="open(index)"
            @close="close"
            class="swipe-lis"
            @click="onClickAction"
           
          >
            <view class="list" @click="goDetails(item.product.id)"  >
              <view class="option" @click.stop="onOptioned(item)">
                <template v-if="item.guige && item.guige.is_ysw == 1 || item.product.is_ysw == 1">
                  <image src="/static/mt-li/disabled.png" />
                </template>
                <template v-else>
                  <image v-if="item.select" src="/static/mt-li/option.png" />
                  <image v-else src="/static/mt-li/no-option.png" />
                </template>
        
              </view>
              <view class="right-section">
                <view class="img">
                  <image
                    class="cover"
                    mode="aspectFill"
                    :src="item.guige && item.guige.pic ? (item.guige[plang('pic')] || item.guige.pic) : (item.product[plang('pic')] || item.product.pic)"
                  />

                  <view class="tag">
                    {{ item.product.is_yf == 1 ? $t('含运费1') : $t('不含运费1')}}
                  </view>
                </view>
                <view class="good-desc">
                  <view class="title ellipsis_two">{{
                    item.product[plang('name')]
                  }}</view>
                  <view class="attr" v-if="item.is_type == 1">{{ item[plang('attr_name')]}}</view>
                  <view class="attr" v-else>{{ item.guige.name ? item.guige[plang('name')] :  item[plang('name')] }}</view>
                  <view class="price-wrap" v-if="item.is_type == 1">
                    <view class="num">{{ item.num }}{{ $t('件2') }}</view>
                   
                    <view class="price"
                      ><text>{{ item.product.currency || '￥'}}</text>{{ item.price }}</view
                    >
                  </view>

                  <view class="price-wrap" v-else>
                    <view class="num">{{ item.num }}{{ $t('件2') }}</view>
                    <view class="price"
                      v-if="item.guige && item.guige.sell_price != '0.00'"
                      ><text>{{ item.product.currency || '￥'}}</text>{{ item.num >= item.guige.qpsl ?  item.guige.pf_price : item.guige.sell_price }}</view
                    >
                    <view class="price"
                      v-else
                      ><text>{{ item.product.currency || '￥'}}</text>{{ item.num >= item.product.qpsl ?  item.product.pf_price : item.product.sell_price }}</view>
                  </view>
                </view>
              </view>
            </view>
          </u-swipe-action>
          <u-empty :text="$t('暂无相关数据')" mode="car" v-if="!list.length " :margin-top="180"></u-empty>
        </view>
      </scroll-view>
    </view>

    <!-- 底部结算区域 -->

    <view class="footer-settle">
      <view class="total-desc">
        <view class="all" @click="onAllOption">
          <image v-if="getTotalObj.isAll" src="/static/mt-li/option.png" />
          <image v-else src="/static/mt-li/no-option.png" />
          <text>{{ $t('全选2') }}</text>
        </view>
        <view class="price-total">
          <text>{{ $t('合计') }}</text>
          <text>{{getTotalObj.currency}}</text>
          <view class="price"> {{ getTotalObj.total }} </view>
        </view>
      </view>
      <view class="settle-btn" @click="goSettled"> {{ $t('结算') }} </view>
    </view>

    <!-- 代收付平台 -->
    <u-popup v-model="showPayPop" mode="bottom" border-radius="24">
      <view class="platform-wrapper">
        <view class="pay-title">{{ $t("商家提供的代收付平台") }}</view>
        <view class="scrol">
          <scroll-view scroll-y>
            <view class="pay-wrapper">
              <view
                :class="['list', index == currentId && 'active']"
                v-for="(item, index) in plateformLists"
                :key="item.id"
                @click="onClickDaifu(index)"
              >
                <view class="name">{{ item[plang('name')] }}</view>
                <view class="right-desc">
                  <view class="e-du"> {{$t("额度")}}：{{item.edu || 0}}{{$t("万2")}} </view>
                  <view class="fee">{{$t("手续费")}}：{{item.feepercent}}%</view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>


        <view class="btn-wrapper">
          <view class="btn" @click="onConfirm">{{ $t('确认') }}</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import CommonHeader from "../components/common-header.vue";
import {
		mapState
	} from 'vuex';

export default {
  components: {
    CommonHeader,
  },
  data() {
    return {
      // scroll状态
      isRefresher: false,
      limit: 12,
      isData: false,
      scrollTop: 0,
      isLoading: false,
      // scroll状态结束
      page: 1,
      list: [],
      options2: [
        {
          text: this.$t("移入收藏"),
          style: {
            backgroundColor: "rgba(255, 106, 0, 1)",
            fontWeight: 400,
            fontSize: "18rpx",
            color: "#fff",
            whiteSpace: "nowrap",
          },
        },
        {
          text: this.$t("删除"),
          style: {
            backgroundColor: "rgba(253, 68, 73, 1)",
            fontWeight: 400,
            fontSize: "18rpx",
            color: "#fff",
          },
        },
      ],
      showPayPop: false, // 展示付款框
      getTotalObj: {
        isAll: false,
        total: 0,
        isHasSelect: false,
        currency: '￥'
      },
      plateformLists: [],
      currentId: 0, // 代付公司id
      title: '',
    };
  },
  computed: {
    // 使用mapState生成计算属性
    ...mapState({
      lang: state => state.commonData.lang,
    })
  },
  watch: {
    list: {
      handler(newValue,oldValue) {
        let total = 0; // 总价格
        let isAll = false; // 判断是否为全选
        let isHasSelect = false; // 购物车中是否有选择了
        let count = 0;
        let noCount = 0;
        let disabledCount = 0;
        let currency = '￥'
        newValue.forEach((ele)=> {
          if (ele.select) {
            currency = ele.product.currency || '￥';
            if (ele?.guige?.qpsl && ele?.guige?.qpsl != 0) {
              total += Number(ele.num >= ele.guige.qpsl ? ele.guige.pf_price : ele.guige.sell_price) * ele.num;
            } else {
              if (ele.is_type == 1) {
                total += Number(ele.price) * ele.num;
              } else {
                total += Number(ele.num >= ele.product.qpsl ? ele.product.pf_price : ele.product.sell_price) * ele.num;
              }
            }
            count++
          } else {
            noCount++;
          }
          if (ele.guige && ele.guige.is_ysw == 1 || ele.product.is_ysw == 1) {
            disabledCount++;
          }

          
        })

        if (newValue.length - disabledCount == count && newValue.length != 0 && count != 0)  {
          isAll = true
        };
        if (newValue.length- disabledCount == noCount - disabledCount)  {
          isHasSelect = false
        } else {
          isHasSelect = true
        };

        console.log(total,'totaltotaltotal')

        this.getTotalObj.total = (total || 0).toFixed(2)
        this.getTotalObj.isAll = isAll
        this.getTotalObj.isHasSelect = isHasSelect
        this.getTotalObj.currency = currency

      },
      deep: true,
      
    }
   
  },
  methods: {
    // 收藏和删除
    async onClickAction(index,index1) {
      let api = index1 == 1 ? 'cartdelete': 'addfavorite';
      try {
        const res = await this.$u.api.shopping[api]({
          id: this.list[index].id,
          proid: this.list[index].product.id,
          guid: this.list[index].guige.id || this.list[index].ggid || '',
          type: 'shop',
          is_cart: 1, // 购物车
        });
        uni.showToast({
          title: res[this.plang('msg')],
        })
        this.list.splice(index,1)
      } catch (error) {
      }
    },
      // 跳转详情页
    goDetails(id) {
      // uni.navigateTo({
      //   url: '/pages/details/shopDetail?id=' + id
      // })
    },
    async onConfirm() {
      if (this.list.length && this.list[this.currentId].id) {
        let prodata = [];
        let cart_id_arr = [];
        let is_type = 0; // 0 非1688 1 1688
        let isCheck = false; // 相同货币规格不可以购买
        let arr = [];
        this.list.forEach((ele)=> {
          if (ele.select) {
            arr.push(ele.product.currency || '￥')
            if (ele.is_type == 1) {
              is_type = 1;
            }
            if (ele.guige.id) {
              prodata.push(`${ele.product.id},${ele.guige.id},${ele.num},${ele.id}`)
            } else {
              prodata.push(`${ele.product.id},${ele.product.id},${ele.num},${ele.id}`)
            }
            cart_id_arr.push(ele.id)

          }
        })

        // 检查所有选中商品的货币单位是否一致
        if (arr.length > 0) {
          const firstCurrency = arr[0];
          isCheck = arr.some(currency => currency !== firstCurrency);
        }

        if (isCheck && cart_id_arr.length > 1) {
          uni.showToast({
            title: this.$t('请选择货币相同的商品进行下单'),
            icon: 'none',
          })
          return;
        }
        let info = {
          prodata: prodata.join('-'),
          df_id: this.plateformLists[this.currentId].id,
          bid: this.bid,
        }
        
        try {
           await this.$u.api.shopping.confimrOrder(info);
         
            uni.navigateTo({
              url: "/pages/confirmOrder/index?info=" + encodeURIComponent(JSON.stringify(info)) + '&is_type=' + is_type + '&cart_id=' + cart_id_arr.join(','),
              success:()=>{
                this.showPayPop = false;
              },
            });
           
        } catch (error) {
          
        }
        
       
        
      }
      
    },
    async goSettled() {
      if (!this.getTotalObj.isHasSelect) {
        uni.showToast({
          title: this.$t('请选择结算的商品'),
          icon: 'none',
        })
        return;
      }
      // this.showPayPop = true;
      try {
        const { data } = await this.$u.api.shopping.dfgsCompany();
        this.plateformLists = data; // 代收付平台
        this.onConfirm();
      } catch (error) {
        console.log(error)
      }


    },
    goback() {
      uni.navigateBack({delta:1,})
    },
    // getprolist 获取列表
    async getData() {
      if (this.isLoading) return;
      this.isLoading = true;
      try {
        const { data } = await this.$u.api.shopping.getShopCart({
          bid: this.bid,
          page: this.page,
        });
        // 首页置空数据
        if (this.page == 1) {
          (data || []).forEach(item => {
            item.select = false;
          });
          this.list = data || [];
        }

        this.isData = true;
        this.isLoading = false;
        this.isRefresher = false;
      } catch (e) {
        this.isLoading = false;
        this.isRefresher = false;
      }
    },
    onOptioned(item) {
      if (item.guige && item.guige.id && item.guige.is_ysw == 1) {
        uni.showToast({
          title: this.$t('商品数量超出库存总数'),
          icon: 'none'
        })
        return;
      }
      if (item.product.is_ysw == 1) {
        uni.showToast({
          title: this.$t('商品数量超出库存总数'),
          icon: 'none'
        })
        return;
      }
      this.$set(item, 'select', !item.select);
      this.$forceUpdate();
    },
    // 全选
    onAllOption() {
      if (!this.getTotalObj.isAll) { // 全选
        this.list = this.list.map((ele)=> {
          if (ele.guige  && ele.guige.is_ysw == 1 || ele.product.is_ysw == 1) {
            ele.select = false
          } else {
            ele.select = true;
          }
          return ele;
        })
      } else {
        this.list = this.list.map((ele)=> {
          ele.select = false
          return ele;
        })
      }
      this.$forceUpdate();
    },
    // 代付公司
    onClickDaifu(id) {
      this.currentId = id;
    },

    close() {
      this.isRefresher = false;
    },
    open(index) {
      this.list[index].show = true;
      this.list.map((val, idx) => {
        if (index != idx) this.list[idx].show = false;
      });
      this.isRefresher = false;
      this.$forceUpdate();
      
    },
    // 触底加载
    lower() {
      if (this.isData) return;
    },
    // 下拉刷新触发
    fresh() {
      this.page = 1;
      this.isRefresher = true;
      this.isData = false;
      this.getData();
    },
    // 下拉刷新复位
    store() {
      this.isRefresher = false;
    },
    // scoll-view结束

  },
  onLoad({ bid,title }) {
    this.bid = bid;
    this.title = title + this.$t('店铺的购物车')
    window.onNativeShow = this.getData;
    this.getData();
  },
  onShow() {
  },
};
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
